<?php
class Image extends AppModel {

	var $name = 'Image';
	var $validate = array(
		'owner_id' => array('numeric'),
		'title' => array('notempty'),
		'active' => array('numeric')
	);
	

	function get_images($model,$ownerId){
		
		$image = $this->find('all',array('conditions'=>array('Image.owner_id'=>$ownerId,'Image.model'=>$model)));
		if (!empty($image)){
			$image = $image[0];
			$image['Image']['files'] = explode(',',$image['Image']['files']);
			return $image['Image'];
		}
		return array();
	}
	
	function explode_images($image){
		if (!empty($image)){
			$image['files'] = explode(',',$image['files']);
			return $image;
		}
	}
	
	function set_images($image){
		$files = "";
		foreach ($image['files'] as $item){
			if (!empty($files)){
				$files = $files.',';
			}
			$files = $files.$item;
		}
		$image['files'] = $files;
		if (empty($image['files'])){
			$this->del($image['id']);	
		}else{
			$this->save($image,false,array('files'));
		}
	}
	
	function save_image($model = null,$ownerId = null,$file=null){
		if (!empty($file)){
			$image = $this->find('first',array('conditions'=>array('owner_id'=>$ownerId,'model'=>$model)));
			if (empty($image)){
				$image['Image']['model'] = $model;
				$image['Image']['owner_id'] = $ownerId;
				$image['Image']['files'] = $file;
				$this->save($image['Image']);
			}else{
				$image['Image']['files'] = $image['Image']['files'].','.$file;
				$this->save($image['Image'],false,array('files'));
			}
			return true;
		}
		return false;
	} 
	
	function delete_img ($model=null,$ownerId = null, $file = null){
		if (!empty($file) && !empty($ownerId)){
			$image = $this->get_images($model,$ownerId);
			foreach($image['files'] as $k=>$imgFile){
				if ($file == $imgFile){
					unset($image['files'][$k]);
					$this->set_images($image);
				}
			}
		}else if(!empty($ownerId)){
			$this->delete(array('conditions'=>array('owner_id'=>$ownerId,'model'=>$model)));
		}
		
		
	}
	
}
?>